$(function(){
	//web socket连接
	var _vsocket = null;
	//聊天对象
	var _vtoUser = null;
	//聊天内容展示
	var _vReceive_text = document.getElementById("show");
	//输入聊天内容
	//var send_text = document.getElementById("textarea");
	
	//是否需要聊天列表
	//if(_visShotcut) {
		//客服聊天列表
		//var shortcutboard = document.getElementById("shortcutboard");
	
	//日期格式化函数
	Date.prototype.pattern = function(fmt) {        
	    var o = {        
	    "M+" : this.getMonth()+1, //月份        
	    "d+" : this.getDate(), //日        
	    "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时        
	    "H+" : this.getHours(), //小时        
	    "m+" : this.getMinutes(), //分        
	    "s+" : this.getSeconds(), //秒        
	    "q+" : Math.floor((this.getMonth()+3)/3),   //季度        
	    "S" : this.getMilliseconds()                //毫秒        
	    };        
	    var week = {        
	    "0" : "\u65e5",        
	    "1" : "\u4e00",        
	    "2" : "\u4e8c",        
	    "3" : "\u4e09",        
	    "4" : "\u56db",        
	    "5" : "\u4e94",        
	    "6" : "\u516d"       
	    };        
	    if(/(y+)/.test(fmt)){        
	        fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));        
	    }        
	    if(/(E+)/.test(fmt)){        
	        fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "\u661f\u671f" : "\u5468") : "")+week[this.getDay()+""]);        
	    }        
	    for(var k in o){        
	        if(new RegExp("("+ k +")").test(fmt)){        
	            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));        
	        }        
	    }        
	    return fmt;        
	};
	
	//消息显示
	var _fAddText = function(textarea)
	{
		_vReceive_text.innerHTML+="</br>"+textarea;
	};
	
	//发送消息至服务端
    var _fSendMsg = function(toUsername, msg, time)
    {
    	var jMsg = {
                 "action":  "textMsg",
                 "msg" : msg,
                 "fromUsername" : _vUser,
                 "toUsername" : toUsername, 
                 createTime: time
	        };
        
        _vsocket.send(JSON.stringify(jMsg));
    };
    
    //添加聊天对象
    var _fAddTalkTo = function(value)
    {
    	var _li = $('<li/>').text(value);
    	_li.attr("id", value);
        $('.chat03_content ul').append(_li);
        $(".chat03_content li").mouseover(function() {
            $(this).addClass("hover").siblings().removeClass("hover");
        }).mouseout(function() {
            $(this).removeClass("hover").siblings().removeClass("hover");
        });
        _li.dblclick(function() {
            $(this).addClass("highlight").siblings().removeClass("highlight");              
            $(".talkTo a").text(value);
            _vtoUser = value;
        });
    };
    
    //add by lin 2013-6-71 10:30
    //chat02_bar里面的img为发送按钮的点击事件e()  发送消息按钮处理事件
    $(".chat02_bar img").click(function() {
    	if(_vtoUser == null) {
            alert("亲，请选择一个人聊天哦。");
        }
    	else {
            var e = new Date,
            f = "";
            f += e.getFullYear() + "-",
            f += e.getMonth() + 1 + "-",
            f += e.getDate() + "  ",
            f += e.getHours() + ":",
            f += e.getMinutes() + ":",
            f += e.getSeconds();
            var g = $("#textarea").val();
            function h(){
            	 -1!=g.indexOf("*#emo_") && (g = g.replace("*#", "<img src='img/").replace("#*", ".gif'/>"), h());
            	
            }
            h();
            var i = "<div>" + _vUser + "&nbsp;&nbsp;&nbsp"+f+"<br/>"+g+"</div>" ;                    
            $("#show").append(i);
            $("#textarea").val("");       
         
            _fSendMsg(_vtoUser, g, e.pattern("yyyy-MM-dd hh:mm:ss"));
       }
    });   
	
	/**
	 * 开始处理socket业务逻辑
	 * */
    _vsocket = new WebSocket('ws://linyuqun.oicp.net:8080/webchat/chatserver');
    _vReceive_text.innerHTML = "</br>正在连接服务器 ……";
	
	//打开Socket 
	_vsocket.onopen = function(event) 
    {
		_fAddText("连接成功！");
        var registObj = {
        	    "action" : "regist",
        	    "role" : "service",
        	    "username" : _vUser,
        	    "password" : _vPw
                };
        _vsocket.send(JSON.stringify(registObj));        
    };
    
    _vsocket.onmessage = function(event) 
    {
        var e =  eval('(' + event.data + ')');  
        //只有已登录的用户才需要好友列表
        if(e.action == 'userlist' && _vUser != null)
       	{
        	$.each(e.userlist, function(key,value){	
        		_fAddTalkTo(value);
        	});
       	} 
        else if(e.action == "textMsg")
        {
            var tx = '' + e.fromUsername + " "
                      + e.createTime + ":" + '</br>'
                      + e.msg;
            _fAddText(tx);
        }
        else if(e.action == "loginUser")
       	{
        	_fAddTalkTo(e.username);
       	}
        else if(e.action == "exitUser")
       	{	
        	$("#shortcutboard" + " #" + e.username).remove();
       	}
        
    };  
    
    _vsocket.onclose = function(event) 
    {
    	_fAddText("连接断开！");
    };
	    
    if(_vsocket==null)
    {
    	_fAddText("连接失败！");
    }
    else
    {
    }    
	
});
